<?php

namespace app\admin\controller;

use app\admin\model\Msg;
use app\admin\model\Role;
use app\admin\model\User as ModelUser;
use app\admin\validate\User as ValidateUser;
use app\BaseController;
use app\index\validate\User as IndexValidateUser;
use app\Request;
use app\service\Tool;
use think\exception\ValidateException;
use think\facade\Db;

class User extends Base
{
    public function index()
    {
        $this->logs('[管理员]用户视图');
        return view();
    }
    public function add()
    {
        $this->logs('[管理员]添加用户视图');
        $roleList = Role::list();
        return view('add', ['roleList' => $roleList]);
    }
    public function doAdd()
    {
        $param = input();
        $param['usernameReg'] = $param['username'];
        $param['passwordReg'] = $param['password'];
        $ip = request()->ip();
        try {
            validate(IndexValidateUser::class)->scene('register')->check($param);
            $userData = ModelUser::where('username', $param['username'])->find();
            if ($userData) return error('该用户名已存在，请更换另一个吧！');
            if (!empty(@$userData['email']) && $userData->email == $param['email']) return error('邮箱已被注册');
            $roleId = '';
            if (array_key_exists('role', $param)) {
                foreach ($param['role'] as $k => $v) {
                    $roleId .= $k . ',';
                }
            }
            $data = [
                'username' => $param['username'],
                'password' => md5(config('secure.secret_key') . $param['password']),
                'nickname' => $param['nickname'],
                'role' => $roleId,
                'email' => $param['email'],
                'head_icon' => '/static/images/headIcon/default.jpeg',
                'ip' => $ip,
            ];
            $res = ModelUser::create($data);
            if ($res) {
                $msg = '欢迎加入到' . config('system.base.title') . '！您已成功注册，期待您在这里分享见解，交流心得，开启精彩讨论之旅！';
                Msg::send(0, $res->id, ['content' => $msg]);
                return success();
            }
            return error('注册失败');
        } catch (ValidateException  $e) {
            return error($e->getMessage());
        }
    }
    public function list()
    {
        $this->logs('[管理员]用户列表');
        $param = input();
        $param['type'] = array_key_exists('type', $param) ? $param['type'] : '';
        $list = ModelUser::list($param);
        return $list;
    }
    public function update($id)
    {
        $this->logs('[管理员]更新用户信息视图');
        $data = ModelUser::find($id);
        $roleList = Role::list();
        return view('update', ['data' => $data, 'roleList' => $roleList]);
    }
    public function uploadHeadIcon()
    {
        $file = request()->file('headIcon');
        $res = Tool::uploadImg($file, 'headIcon');
        return $res;
    }
    // 审核全部用户
    public function examineAll()
    {
        $res = ModelUser::where('status', 2)->update(['status' => 1]);
        if ($res) return success();
        return error();
    }
    public function doUpdate()
    {
        $this->logs('[管理员]更新用户信息');
        if (Request()->isPost()) {
            $param = input();
            $id = $param['id'];
            if (!empty(@$param['password'])) {
                $param['password'] = md5(config('secure.secret_key') . $param['password']);
            } else {
                unset($param['password']);
            }
            $user = ModelUser::where('id' , $id);
            if ($user->findOrEmpty()->isEmpty()) return error('不存在该用户');
            $userData = $user->find();
            if($userData['nickname'] != @$param['nickname'])
            {
                $hasNick = Db::name('user')->where('nickname' ,@$param['nickname'])->find();
                if($hasNick) return error('已存在该昵称，请更换！');
            }
            if($userData['username'] != @$param['username'])
            {
                $hasNick = Db::name('user')->where('username' ,@$param['username'])->find();
                if($hasNick) return error('已存在该用户名，请更换！');
            }
            $param['role'] = Role::ArrtoStr(@$param['role']) ?? '';
            $res = ModelUser::update($param);
            if ($res) return success();
            else return error();
        }
    }

    public function del($id)
    {
        $this->logs('[管理员]删除用户');
        return (new ModelUser())->del($id);
    }
}
